package com.platform.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.platform.common.utils.JedisUtil;
import com.platform.common.utils.Query;
import com.platform.modules.sys.entity.SysCacheEntity;
import com.platform.modules.sys.entity.SysDictEntity;
import com.platform.modules.sys.service.SysCacheService;

/**
 * @author 肖亮
 */
@Service("sysCacheService")
public class SysCacheServiceImpl implements SysCacheService {
	@Autowired
	private JedisUtil jedisUtil;

	@Override
	public List<SysCacheEntity> queryAll(Map<String, Object> params) {
		SysCacheEntity sysCacheEntity;
		List<SysCacheEntity> result = new ArrayList<>();

		String pattern = params.get("pattern").toString();
		// 获取所有key
		Set<String> keySet = jedisUtil.keys(pattern);
		for (String key : keySet) {
			sysCacheEntity = new SysCacheEntity();
			
			try {
				sysCacheEntity.setValue(JSONObject.toJSON(jedisUtil.getObject(key)).toString());
				sysCacheEntity.setCacheKey(key);
				sysCacheEntity.setSeconds(jedisUtil.ttl(key));
				result.add(sysCacheEntity);
			} catch (Exception e) {
				sysCacheEntity.setValue("");
			}
			
			
		}
		return result;
	}

	@Override
	public int deleteBatch(String[] keys) {
		for (String key : keys) {
			jedisUtil.del(key);
			jedisUtil.delObject(key);
		}
		return keys.length;
	}

	@Override
	public IPage queryPage(Map<String, Object> params) {
		SysCacheEntity sysCacheEntity;
		List<SysCacheEntity> result = new ArrayList<>();

		String pattern = (String) params.get("pattern");
		// 获取所有key
		Set<String> keySet = jedisUtil.keys(pattern);
		for (String key : keySet) {
			sysCacheEntity = new SysCacheEntity();
			try {
				sysCacheEntity.setValue(JSONObject.toJSON(jedisUtil.getObject(key)).toString());
				sysCacheEntity.setCacheKey(key);
				sysCacheEntity.setSeconds(jedisUtil.ttl(key));
				result.add(sysCacheEntity);
			} catch (Exception e) {
				sysCacheEntity.setValue("");
			}
			
		}
		IPage<SysCacheEntity> page = new Query<SysCacheEntity>(params).getPage();
		return page.setRecords(result);
	}
}
